<?php
namespace app\http;

use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * Class UdpServer
 * @package app\http
 * 启动: php think udp:start
 */
class UdpServer extends Command
{
    protected $server;

    // 命令行配置函数
    //tp5 命令行配置详细用法 https://blog.csdn.net/kelinfeng16/article/details/88549717
    protected function configure()
    {
        // setName 设置命令行名称
        // setDescription 设置命令行描述
        $this->setName('udp:start')->setDescription('Start UDP Server!');
    }

    // 设置命令返回信息
    protected function execute(Input $input, Output $output)
    {
        $this->server = new \swoole_server("127.0.0.1", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);

        // 设置 server 运行前各项参数
        $this->server->set([
            'worker_num' => 4,
            'daemonize'  => false,
        ]);

        // 注册回调函数
        $this->server->on('Start', [$this, 'onStart']);
        $this->server->on('Packet', [$this, 'onPacket']);
        $this->server->on('Close', [$this, 'onClose']);

        // 启动服务器
        $this->server->start();
    }

    // 主进程启动时回调函数
    public function onStart(\swoole_server $server)
    {
        echo "Start\n";
    }

    // 接受数据回调
    public function onPacket(\swoole_server $server, $data, $clientInfo)
    {
        $server->sendto($clientInfo['address'], $clientInfo['port'], "Server " . $data);
        var_dump($data);
        var_dump($clientInfo);
    }

    // 关闭连时回调函数
    public function onClose(\swoole_server $server, $fd, $from_id)
    {
        echo "Close\n";
    }
}